package com.wordpoi.utils.excel;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author ActStrady
 * @date 2019/12/4
 */
public class ExcelParser {
    /**
     * 读取 Excel 数据并处理
     */
    protected List<List<String>> readExcel(String fileName) throws IOException, InvalidFormatException {
        List<List<String>> table = new ArrayList<>();
        InputStream in = new FileInputStream(fileName);
        // 读取xlsx 不分xlsx和xls
        final Workbook workbook = WorkbookFactory.create(in);
        // sheet
        Sheet sheet = workbook.getSheetAt(0);
        //获取总行数
        int rows = sheet.getPhysicalNumberOfRows();
        for (int i = 0; i < rows; i++) {
            Row row = sheet.getRow(i);
            List<String> rowArray = new LinkedList<>();
            table.add(rowArray);
            // 获取总列数
            int cols = row.getPhysicalNumberOfCells();
            for (int j = 0; j < cols; j++) {
                table.get(i).add(row.getCell(j).getStringCellValue());
            }
        }
        in.close();
        workbook.close();
        return table;
    }

    private static Object getValue(Cell cell) {
        Object obj = null;
        switch (cell.getCellTypeEnum()) {
            case BOOLEAN:
                obj = cell.getBooleanCellValue();
                break;
            case ERROR:
                obj = cell.getErrorCellValue();
                break;
            case NUMERIC:
                obj = cell.getNumericCellValue();
                break;
            case STRING:
                obj = cell.getStringCellValue();
                break;
            default:
                break;
        }
        return obj;
    }
}
